#!/usr/bin/env node

import sharp from 'sharp';
import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import { fileURLToPath } from 'url';
import inquirer from 'inquirer'; // 使用inquirer进行交互式选择

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 设备类型及其对应宽度
const DEVICE_WIDTHS = {
  desktop: 4800,
  mobile: 2700
};

// 命令行参数处理
const args = process.argv.slice(2);

// 显示帮助信息
function showHelp() {
  console.log(`
${chalk.blue.bold('imgresizer - 专业图片转换工具')}

${chalk.green('使用方式:')}
  imgresizer [图片路径] [设备类型]

${chalk.yellow('功能:')}
  根据设备类型将图片转换为合适尺寸的高质量PNG格式
  - 电脑/平板: ${DEVICE_WIDTHS.desktop}px宽度
  - 手机: ${DEVICE_WIDTHS.mobile}px宽度

${chalk.cyan('示例:')}
  imgresizer ~/Pictures/photo.jpg desktop
  imgresizer /Users/name/Documents/image.webp mobile

${chalk.magenta('参数选项:')}
  -h, --help     显示帮助信息
  -v, --version  显示版本信息
  desktop        电脑/平板尺寸 (${DEVICE_WIDTHS.desktop}px)
  mobile         手机尺寸 (${DEVICE_WIDTHS.mobile}px)
  `);
}

async function selectDeviceType() {
  const answers = await inquirer.prompt([
    {
      type: 'list',
      name: 'deviceType',
      message: '请选择设备类型:',
      choices: [
        { name: '电脑/平板 (桌面设备)', value: 'desktop' },
        { name: '手机 (移动设备)', value: 'mobile' }
      ],
      default: 'mobile'
    }
  ]);
  return answers.deviceType;
}

async function main() {
  if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
    showHelp();
    return;
  }

  if (args.includes('--version') || args.includes('-v')) {
    try {
      const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
      console.log(`imgresizer v${packageJson.version}`);
    } catch (e) {
      console.log(`imgresizer v1.0.0`);
    }
    return;
  }

  const inputPath = path.resolve(args[0]);
  
  // 确定设备类型（通过参数或交互选择）
  let deviceType = args[1] || 'mobile';
  
  try {
    deviceType = await selectDeviceType();
  } catch (promptError) {
    console.error(chalk.red('❌ 设备类型选择失败, 默认使用 mobile'));
    deviceType = 'mobile';
  }

  try {
    await processImage(inputPath, deviceType);
  } catch (error) {
    console.error(chalk.red(`❌ 错误: ${error.message}`));
    process.exit(1);
  }
}

async function processImage(inputPath, deviceType) {
  console.log(chalk.blue(`🔍 正在处理: ${inputPath}`));
  console.log(chalk.blue(`📱 设备类型: ${deviceType === 'desktop' ? '电脑/平板' : '手机'}`));
  
  // 确定目标宽度
  const targetWidth = DEVICE_WIDTHS[deviceType];
  
  // 验证文件是否存在
  if (!fs.existsSync(inputPath)) {
    throw new Error('文件不存在');
  }
  
  // 检查是否为图片文件
  const validExtensions = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp', '.tiff'];
  const ext = path.extname(inputPath).toLowerCase();
  
  if (!validExtensions.includes(ext)) {
    throw new Error('不支持的图片格式');
  }
  
  // 获取文件元数据
  const image = sharp(inputPath);
  const metadata = await image.metadata();
  
  // 计算新高度
  const newHeight = Math.round(targetWidth * metadata.height / metadata.width);
  
  // 创建输出路径
  const parsed = path.parse(inputPath);
  let outputFileName;

  if (deviceType === 'desktop') {
    outputFileName = `${parsed.name}_${targetWidth}_pc.png`;
  } else {
    outputFileName = `${parsed.name}_${targetWidth}_iphone.png`;
  }

  const outputPath = path.join(parsed.dir, outputFileName);

  // 避免覆盖原始文件
  if (fs.existsSync(outputPath)) {
    // 时间戳限制到分即可
    const now = new Date();
    const timestamp = `${now.getFullYear().toString().substr(-2)}${String(now.getMonth()+1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}`;
    outputFileName = `${parsed.name}_${timestamp}_${targetWidth}_${deviceType === 'desktop' ? 'pc' : 'iphone'}.png`;
  }
  
  // 处理图片
  console.log(chalk.yellow(`🖼️ 原始尺寸: ${metadata.width}×${metadata.height}`));
  console.log(chalk.yellow(`🆕 目标尺寸: ${targetWidth}×${newHeight}`));
  console.log(chalk.blue('⚙️ 正在转换并优化...'));
  
  const startTime = Date.now();
  
  await image
    .resize({
      width: targetWidth,
      height: newHeight,
      fit: 'contain',
      withoutEnlargement: true
    })
    .toFormat('png', {
      compressionLevel: 9,
      quality: 90,
      effort: 10,
      palette: true,
      colors: 256,
      dither: 1.0,
      force: true
    })
    .toFile(outputPath);
  
  const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
  
  // 输出结果
  console.log(chalk.green(`✅ 转换成功! (耗时: ${elapsedTime}秒)`));
  console.log(chalk.green(`📁 输出文件: ${outputPath}`));
}

// 执行主函数
main().catch(error => {
  console.error(chalk.red(`❌ 未处理的错误: ${error.message}`));
  process.exit(1);
});